package corej.prj.chatRoom.huxz;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ChatServerHuxz {

    public static void main(String[] args) throws Exception {
        // JDK5.0�е��÷������ͱ��
        List<Socket> sockets = new ArrayList<Socket>();
        ServerSocket ss = new ServerSocket(9000);
        while (true) {
            Socket s = ss.accept();
            sockets.add(s);
            Thread t = new ServerThread(s, sockets);
            t.start();
        }

    }

}

class ServerThread extends Thread {
    Socket s;

    List sockets;


    public ServerThread(Socket s, List sockets) {
        super();
        this.s = s;
        this.sockets = sockets;
    }

    public void run() {
        try {
            // 1.��������Ķ���
            BufferedReader in = new BufferedReader(new InputStreamReader(s
                    .getInputStream()));
            // 2.�����:�ѭ��
            while (true) {

                // 2.1.�ȴ���ܴӿͻ��˷�4����Ϣ�����û�з�����ȴ�
                String text = in.readLine();
                // 2.2.����Client��List���Ѵ��������еõ������ݷ������ͻ��˵�����
                if (text == null)
                    break;
                Iterator it = sockets.iterator();
                while (it.hasNext()) {
                    Socket s2 = (Socket) it.next();
                    PrintWriter out = new PrintWriter(s2.getOutputStream());
                    out.println(text);
                    out.flush();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // ��Socket��List���Ƴ�
            sockets.remove(s);
            try {
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

}
